<?php

// +----------------------------------------------------------------------
// | 版权所有 2017-2027 云南环拓科技有限公司，并保留所有权利。
// +----------------------------------------------------------------------
// | Copyright (c) 2017-2027 http://www.yn123.com All rights reserved.
// +----------------------------------------------------------------------
// | Notice: This code is not open source, it is strictly prohibited
// |         to distribute the copy, otherwise it will pursue its
// |         legal responsibility.
// | 注意：  这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用,
// |        不允许对程序代码以任何形式任何目的的再发布。
// +----------------------------------------------------------------------
// | Author: feraner <feraner@163.com> 
// | Date: 2019/11/28
// +----------------------------------------------------------------------

namespace app\index\controller\api;

use app\common\facade\Arr;
use app\common\services\wechattemplate\WechatPayTemplateService;
use app\wechat\service\WechatService;
use think\App;
use think\Controller;
use think\Db;

/**
 * 微信支付回调类
 * Class WechatPayNotify
 * @package app\index\controller\api
 * @author feraner<feraner@163.com>
 * @date 2019/11/28
 */
class WechatPayNotify extends Controller
{

    public function __construct(App $app = null)
    {
        parent::__construct($app);
    }


    /**
     * 微信支付购买豆回调
     * @throws \WeChat\Exceptions\InvalidResponseException
     */
    public function payBeanNotify()
    {
        $wechatPayServer = WechatService::WePayOrder();
        $returnData = $wechatPayServer->getNotify();

        if ($returnData['return_code'] === 'SUCCESS' && $returnData['result_code'] === 'SUCCESS') {
            try {
                Db::startTrans();

                $chargeActiveId = 0;
                //查看是否是活动充值
                if ($attachStr = Arr::get($returnData, 'attach', false)) {
                    $activeArr = explode('=', $attachStr);
                    if (Arr::valueEq($activeArr, 0, 'activeId') &&
                    Arr::get($activeArr, 1)) {
                        $chargeActiveId = Arr::get($activeArr, 1, 0);
                    }
                }

                //1： 获取充值记录
                $orderNo = Arr::get($returnData, 'out_trade_no', '');
                $transactionId = Arr::get($returnData, 'transaction_id', '');
                $chargeInfo = Db::name('user_charge')
                    ->where('order_no', $orderNo)
                    ->find() ?: [];
                
                
                

                //2: 修改订单状态
                $result = Db::name('user_charge')
                    ->where('id', Arr::get($chargeInfo, 'id', 0))
                    ->update([
                        'updated_at'        => time(),
                        'refund_fee'        => $transactionId,
                        'finished_time'     => time(),
                        'status'            => 1
                    ]);
                if ($result) {

                    //计算汇豆
                    if ($chargeActiveId) {
                        list($beanRate, $giveBeanRate, $giveCreditsRate) = $this->__getActiveInfo($chargeActiveId);
                    } else {
                        $beanRate = sysconf('publish_job_bean_rate') ?: 0;
                        $giveBeanRate = sysconf('recharge_bean_give_bean') ?: 0;
                        $giveCreditsRate = sysconf('recharge_bean_give_credits') ?: 0;
                    }


                    $buyBean = Arr::get($chargeInfo, 'money', 0) * $beanRate;
                    $giveBean = Arr::get($chargeInfo, 'money', 0) * $giveBeanRate;
                    $giveCredits = Arr::get($chargeInfo, 'money', 0) * $giveCreditsRate;

                    //3: 增加用户的汇豆数量
                    $result = Db::name('user_wallet')
                        ->where('user_id', Arr::get($chargeInfo, 'user_id'))
                        ->update([
                            'publish_bean'          => Db::raw('publish_bean + ' . Arr::get($chargeInfo, 'bean', 0)),
                            'credits'               => Db::raw('credits + ' . $giveCredits),
                            'updated_at'            => time()
                        ]);
                    if ($result) {
                        //4:  发布豆增加记录表 + 积分表
                        if ($giveCredits) {
                            $result = Db::name('user_credits_log')
                                ->insertGetId([
                                    'user_id'       => Arr::get($chargeInfo, 'user_id'),
                                    'credits'       => $giveCredits,
                                    'type'          => 1,
                                    'kind'          => 2,
                                    'created_at'    => time(),
                                    'updated_at'    => time()
                                ]);
                        }
                        if ($result) {
                            Db::commit();
                            (new WechatPayTemplateService())->sendBuyBeanOk($chargeInfo);
                            // 返回接收成功的回复
                            ob_clean();
                            echo $wechatPayServer->getNotifySuccessReply();
                        }
                    }
                } else {
                    throw new \Exception('修改订单失败');
                }
            } catch (\Exception $e) {
                Db::rollback();
            }
        }

        exit();
    }


    /**
     * 获取充值活动的充值汇率
     * @param $activeId
     *
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function __getActiveInfo($activeId)
    {
        $activeInfo = Db::name('charge_active')
            ->where('id', $activeId)
            ->find() ?: [];
        return [
            Arr::get($activeInfo, 'publish_bean', 0),
            Arr::get($activeInfo, 'charge_bean', 0),
            Arr::get($activeInfo, 'charge_credit', 0)
        ];
    }





}
